<template>
  <div class="detail">
    <div class="nav">实名认证
      <button @click="delLoginOut" class="tuit">退出</button>
    </div>
    <!-- <div class="user-detail-top">基本信息</div> -->
    <div class="user-detail-group">
        <!-- <div class="card_main">
          <div class="acc_sc negative">
            <div id="pic0">
              <img class="acc_imgin" src="./images/negative.jpg">
            </div>
            <input type="file" name="backFile" id="file0" accept="image/*" class="ph08">
          </div>
          <p>点击上传（国徽面）照片</p>
        </div>
        <div class="card_main">
          <div class="acc_sc positive">
            <div id="pic1">
                <img class="acc_imgin" src="./images/positive.jpg">
            </div>
            <input type="file" name="faceFile" id="file1" accept="image/*" class="ph08">
          </div>
          <p>点击上传（人像面）照片</p>
        </div>  -->
       
        <!-- <div class="rz-picter">
          <img src="./images/negative.jpg" />
          <p>上传国辉页</p>
        </div>
        <div class="rz-picter">
          <img src="./images/positive.jpg" />
          <p>上传人像页</p>
        </div> -->

        <div class="user-item">
          <span>证件类型</span>
          <span><input type="text" v-model="identityType" readOnly><i class="iconfont icon-right_3"></i></span>
        </div>

        <div class="rz-picter-main">
          <div class="h3">上传身份证</div>
          <div class="rz-picter">
            <img :src="avatar" class="img-avatar">
            <input type="file" accept="image/gif,image/jpeg,image/jpg,image/png" @change="changeImage($event)" class="uppic">
           
          </div>
          <p>点击上传（国徽面）照片</p>
          <div class="rz-picter">
            <img :src="avatar1" class="img-avatar">
            <input type="file" accept="image/gif,image/jpeg,image/jpg,image/png" @change="changeImage1($event)" class="uppic">
           
          </div>
          <p>点击上传（人像面）照片</p>
        </div>
       
        <div class="user-item">
            <span>真实姓名</span>
            <span><input type="text" v-model="name" placeholder="拍照可智能识别"></span>
        </div>
        <div class="user-item">
          <span>身份证号</span>
          <span><input type="text" v-model="IdNumber" placeholder="拍照可智能识别"></span>
        </div>
        <!-- <div class="user-item">
            <span>手机号码</span>
            <span>{{user_phone}}</span>
        </div> -->
        <div class="user-item">
          <span>手机号码</span>
          <span><input type="text" v-model="user_phone" readOnly></span>
        </div>
        <div class="user-item">
          <span>验证码</span>
          <span><input type="text" v-model="verifyCode" maxlength="6" placeholder="请输入验证码" style="width: 77%;text-align: left;padding-right: 25px;"></span>

          <button 
          v-if="!countDown"
          class="get-verification phone_right"
          @click.prevent="getPhone">
          获取验证码
        </button>
          <button v-else disabled="disabled" class="get-verification" >已发送({{countDown}}s)</button>
        </div>
        <div class="user-item" @click="sheetVisible = true">
            <span>性别</span>
            <span><input type="text" v-model="user_sex" placeholder="请选择"><i class="iconfont icon-right_3"></i></span>
        </div>
        <button @click="handleUserAuth" class="tijiao">提交认证</button>
    </div>
    <!-- 选择性别 -->
    <mt-actionsheet
    :actions="actions"
    v-model="sheetVisible">
    </mt-actionsheet>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getUserInFo ,credentialVerify, getSenderVerifyCode, userAuth } from "./../../api/index";

import { Toast, MessageBox, Indicator } from 'mint-ui';
import {mapActions} from 'vuex'
export default {
  name: "Verified",
  data() {
    return {
      name:"",
      IdNumber:"",
      user_phone: "",
      user_sex: "",
      verifyCode:"",
      identityType:"居民身份证",
      countDown: 0, //倒计时
      avatar: require('./images/negative.jpg'),
      avatar1: require('./images/positive.jpg'),
      // 1.性别
      actions: [
        { name: "男", method: this.handleSexClick },
        { name: "女", method: this.handleSexClick }
      ],
      sheetVisible: false,
    };
  },
  computed: {
    ...mapState(["userInfo"])
  },
  mounted() {
    //this.user_sex = this.userInfo.user_sex;
    //this.user_phone = this.userInfo.user_phone || "";
  },
  created() {
    this.getUserInFo();
  },
  methods: {
    ...mapActions(["Logout","asyncgetUserInFo"]),
	//...mapState(["userInfo"]),
    delLoginOut() {
        MessageBox.confirm('确定要退出登录吗').then(action => {
            // console.log(action);
            if("confirm" === action) {
            this.Logout({});  //请求接口
            //返回主界面
                this.$router.push('/login') 
            }
        }).catch(()=>{});
    },
    handleSexClick(props) {
      //选择性别
      // console.log(props)
      this.user_sex = props.name;
    },
    getUserInFo(){
		  getUserInFo().then(response => {
        this.user_phone = response.data.cellphone

			//commit(USER_INFO, { userInfo: response.msg });
			
			//this.asyncgetUserInFo();
		}).catch(()=>{});
	},
    changeImage(e) {
            var that = this
            if (e.target.files[0]) {
              var file = e.target.files[0]
              var reader = new FileReader()
              reader.readAsDataURL(file)
              reader.onload = function() {
                img.src = this.result
              }
              var img = new Image,
              width = 1024, //image resize   压缩后的宽
              quality = 0.8, //image quality  压缩质量
              canvas = document.createElement("canvas"),
              drawer = canvas.getContext("2d");
              img.onload = function() {
                canvas.width = width;
                canvas.height = width * (img.height / img.width);
                drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                var base64 = canvas.toDataURL("image/jpeg", quality); // 这里就拿到了压缩后的base64图片
                that.avatar = base64;
              }
          }   
    },
    changeImage1(e) {
            var that = this
            if (e.target.files[0]) {
              var file = e.target.files[0]
              var reader = new FileReader()
              reader.readAsDataURL(file)
              reader.onload = function() {
                img.src = this.result
              }
              var img = new Image,
              width = 1024, //image resize   压缩后的宽
              quality = 0.8, //image quality  压缩质量
              canvas = document.createElement("canvas"),
              drawer = canvas.getContext("2d");
              img.onload = function() {
                canvas.width = width;
                canvas.height = width * (img.height / img.width);
                drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                var base64 = canvas.toDataURL("image/jpeg", quality); // 这里就拿到了压缩后的base64图片
                that.avatar1 = base64;
              }
      }
      setTimeout(function () {
        console.log(that.avatar1);
        const fd = new FormData()
        fd.append('faceFile', that.avatar1);
        Indicator.open({text: '识别中，请稍等...',spinnerType: 'fading-circle'});
        credentialVerify(fd).then(response => {
            Toast({
              message: "识别成功",
              position: "center",
              duration: 2000
            });
            Indicator.close();
            that.name = response.data.realName;
            that.IdNumber = response.data.cardNo;
            that.user_sex = response.data.gender;
        });
      }, 1000);
    },

    async getPhone() {
       getSenderVerifyCode(this.name,this.IdNumber).then(response => {
          Toast({
            message: response.msg,
            position: "center",
            duration: 2000
          });
          this.daojishi();
        }).catch(()=>{});
    },
    //验证码倒计时
    async daojishi(){
      this.countDown = 60;
        this.timer = setInterval(() => {
          this.countDown--;
          //判断
          if (this.countDown == 0) {
            clearInterval(this.timer);
          }
        }, 1000);
    },
    // 提交实名认证
    async handleUserAuth() {
      var that = this
      if (this.avatar.indexOf('data:image')) {
        Toast({ message: "请上传国徽面" });
        return;
      }else if (this.avatar1.indexOf('data:image')) {
        Toast({ message: "请上传人像面" });
        return;
      }else if (!this.name) {
        Toast({ message: "真实姓名不能为空" });
        return;
      } else if (!this.IdNumber) {
        Toast({ message: "身份证号不能为空" });
        return;
      } else if (!this.verifyCode) {
        Toast({ message: "验证码不能为空" });
        return;
      } else if (!this.user_sex) {
        Toast({ message: "请选择性别" });
        return;
      }
      that.identityType = "0";
      Indicator.open({text: '认证中...',spinnerType: 'fading-circle'});
      userAuth(that.name,that.IdNumber,that.verifyCode,that.avatar,that.avatar1,that.identityType,that.user_sex).then(response => {
          Indicator.close();
          Toast({
            message: "认证成功,将会跳转到签署",
            position: "center",
            duration: 2000,
          });
          console.log(response.data.url);
          if(response.data.url!=""){
            //setTimeout(location.href = response.data.url, 200 )
            setTimeout(function(){location.href = response.data.url;}, 3000 )
          }
        }).catch(()=>{});

    //   let result = await UserUpdate(
    //     this.userInfo.token,
    //     this.user_sex,
   
    //   );
    // //   console.log(result);
    // // 提示用户
    // Toast({
    //     message: result.message,
    //     position: 'bottom',
    //     duration: 2000
    // });
    // // 返回主界面
    // if(result.success_code == 200){
    //     // 更新本地数据
    //     this.$store.dispatch('getUserInFo');
    //     //返回主界面
    //     setTimeout(() => {
    //         this.$router.replace('/me');
    //     }, 2000);
    // }
    }
  }
};
</script>

<style scoped lang="stylus" ref="stylesheet/stylus">
.detail {
    width: 100%;
    height: 100%;
    /* .user-detail-top {
        width: 100%;
        height: 60px;
        line-height: 60px;
        font-weight: bold;
    } */
    .tuit{
        right: 0;
        left:auto;
        color: #07f;
        font-size: 14px;
    }
    .user-detail-group {
        overflow: hidden;
        .rz-picter-main{
          background: #fff;
          margin-top:5px;
          margin-bottom:5px;
          .h3{
            font-weight:bold;
            font-size: 16px;
            padding: 25px 10px 20px 10px;
          }
          p{
            text-align:center;
            padding-bottom:30px;
            font-size: 14px;
            color: #aaa;
          }
        }
        .rz-picter{
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding-bottom: 10px;
         
          .uppic {
            width 85%
            height 190px
            margin 0 auto
            opacity 0
            z-index 1
          }
          .img-avatar {
            position absolute
            width 85%
            height 190px
          }
        }
        .user-icon {
            height: 60px;
            padding: 0 10px;
            background-color: #fff;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
 
            img {
                width: 50px;
                border-radius: 50%;
            }
        }

        .user-item {
            /* height: 70px; */
            font-size: 14px;
            padding: 0 10px;
            background-color: #fff;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            .get-verification {
              position: absolute;
              top: 27px;
              right: 10px;
              transform: translateY(-50%);
              border: 0;
              color: #ccc;
              font-size: 15px;
              background: transparent;

              &.phone_right {
                color: #0077ff;
              }
            }
            input {
                border: none;
                outline: none;
                text-align: right;
                height: 55px;
                line-height: 55px;
                font-size: 15px;
            }
            
        }

        .tijiao {
            width: 90%;
            height: 42px;
            line-height: 42px;
            background-color: #07f;
            text-align: center;
            margin: 30px 5% 40px 5%;
            border: none;
            font-size: 16px;
            color: #fff;
            border-radius: 4px;
        }
    }

    .right-title-color {
        color: #999;
        font-size: 14px;
    }
}
</style>
